/*
 * Copyright (c) 2013 WDCY Information Technology Co. Ltd
 * www.wdcy.cc
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * WDCY Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with WDCY Information Technology Co. Ltd.
 */
package com.monkey.web.platform.controller;

import com.monkey.core.repository.hibernate.HibernateUtils;
import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.web.dto.response.monitor.JPAConfigResponseJSONDto;
import com.monkey.web.dto.response.monitor.LoadMemoryInfoResponseJSONDto;
import com.monkey.web.dto.response.monitor.LoadRuntimeOsInfoResponseJSONDto;
import com.monkey.web.dto.response.monitor.SystemStatusResponseJSONDto;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.stat.Statistics;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Map;

/**
 * @author Wu Tianqiang
 */
@Controller
@RequestMapping(value = "/m/monitor", produces = {MediaType.APPLICATION_JSON_VALUE})
public class MonitorController {

    @PersistenceContext
    private EntityManager em;

    @RequestMapping(value = "/runtime_os", method = RequestMethod.GET)
    public MonkeyResponseDto runtimeOSInfo() {
        return new LoadRuntimeOsInfoResponseJSONDto().success("load.runtime.os.info.success");
    }

    @RequestMapping(value = "/memory", method = RequestMethod.GET)
    public MonkeyResponseDto memoryInfo() {
        return new LoadMemoryInfoResponseJSONDto().success("load.memory.info.success");
    }

    @RequestMapping(value = "/gc", method = RequestMethod.GET)
    public MonkeyResponseDto gc() {
        System.gc();
        return new MonkeyResponseDto().success("system.monitor.gc.success");
    }

    @RequestMapping(value = "/jpa_config", method = RequestMethod.GET)
    public MonkeyResponseDto jpaConfig() {
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory(em);
        Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
        Map<String, Object> properties = em.getEntityManagerFactory().getProperties();
        return new JPAConfigResponseJSONDto(allClassMetadata, properties).success("load.jpa.config.success");
    }

    @RequestMapping(value = "/system_status", method = RequestMethod.GET)
    public MonkeyResponseDto systemStatus() {
        Statistics statistics = HibernateUtils.getSessionFactory(em).getStatistics();
        return new SystemStatusResponseJSONDto(statistics).success("load.system.status.success");
    }


}